using System;
using System.Data;
using System.Configuration;
using System.Collections.Generic;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using TanashCMS.Business;
using TanashCMS.Business.Task;

public partial class manager_inventory_Categories : CMSManagementPageBase
{
    private FormViewMode mFormMode { get { return ViewState["categoryFormMode"] != null ? (FormViewMode)ViewState["categoryFormMode"] : FormViewMode.Insert; } set { ViewState["categoryFormMode"] = value; } }
    protected int _categoryId { get { return Request.QueryString["cid"] != null ? int.Parse(Request.QueryString["cid"]) : 0; } }
    private string selectedNodeValue;
    private TreeNode selectedNode = null;

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack && _categoryId != 0)
        {
            mFormMode = FormViewMode.Edit;
            Category cat = Category.Get(_categoryId);

            btnEdit.Enabled = true;
            btnEdit.Text = "Edit " + HttpUtility.HtmlDecode(cat.Title);

            btnCustomize.Text = "Customise " + HttpUtility.HtmlDecode(cat.Title);
            btnCustomize.Enabled = true;
            fieldSelectedCategory.Value = _categoryId.ToString();
        }
    }

    protected override void OnInit(EventArgs e)
    {
        if (!IsPostBack)
            DataBind();

        base.OnInit(e);
    }

    /*
    protected void tvCategories_DataBinding(object sender, EventArgs e)
    {
        List<Category> cats = Category.List(mWebsite.ID, 0);
        foreach (Category cat in cats)
        {
            TreeNode node = new TreeNode();
            node.Text = cat.Title;
            node.Value = cat.ID.ToString();

            BindChildNodes(node);
            tvCategories.Nodes.Add(node);
            node.Expand();
        }
        
        tvCategorySelector.ExpandAll();
    }
    */
    private void BindChildNodes(TreeNode ParentNode)
    {
        List<Category> cats = Category.List(mWebsite.ID, int.Parse(ParentNode.Value));
        foreach (Category cat in cats)
        {
            TreeNode node = new TreeNode();
            node.Text = cat.Title;
            node.Value = cat.ID.ToString();
            if (_categoryId == cat.ID) node.Select();

            BindChildNodes(node);
            ParentNode.ChildNodes.Add(node);
            ParentNode.Expand();
        }
    }
    
    protected void ddlAction_SelectedIndexChanged(object sender, EventArgs e)
    {
        switch(ddlAction.SelectedIndex)
        {
            case 1:
                DeleteCategory();
                break;
            case 2:
                MoveUp();
                break;
            case 3:
                MoveDown();
                break;
        } 
        
        ResetForm();

        ddlAction.SelectedIndex = 0;
    }


    private void MoveUp()
    {
        new InventoryTask(mWebsite.ID).CategoryOrderUp(_categoryId, User.Identity.Name);

        if (!mWebsite.NeedsPublish)
        {
            Configuration.GetCurrentSession().Save(mWebsite);
            Configuration.GetCurrentSession().Flush();
        }
        ResetForm();
        DataBind();
    }

    private void MoveDown()
    {
        new InventoryTask(mWebsite.ID).CategoryOrderDown(_categoryId, User.Identity.Name);

        if (!mWebsite.NeedsPublish)
        {
            Configuration.GetCurrentSession().Save(mWebsite);
            Configuration.GetCurrentSession().Flush();
        }
        ResetForm();
        DataBind();
    }

    private void DeleteCategory()
    {
        Category cat = Category.Get(_categoryId);
        int parentId = cat.ParentID;
        cat.State = CMSObjectState.Deleted;
        cat.Save();

        if (!mWebsite.NeedsPublish)
            Configuration.GetCurrentSession().Save(mWebsite);

        Configuration.GetCurrentSession().Flush();

        Response.Redirect("Categories.aspx?cid=" + parentId, true);
    }

    protected void btnSelectParentCat_Click(object sender, EventArgs e)
    {
    }
    protected void tvCategorySelector_DataBinding(object sender, EventArgs e)
    {
        tvCategorySelector.Nodes.Clear();
        List<Category> cats = Category.List(mWebsite.ID, 0);
        TreeNode rootNode = new TreeNode();
        rootNode.Text = "None (root level)";
        rootNode.Value = "0";
        rootNode.Select();
        tvCategorySelector.Nodes.Add(rootNode);

        foreach (Category cat in cats)
        {
            TreeNode node = new TreeNode();
            node.Text = cat.Title;
            node.Value = cat.ID.ToString();
            if (_categoryId == cat.ID) node.Select();
            BindChildNodes(node);
            tvCategorySelector.Nodes.Add(node);
        }
        tvCategorySelector.ExpandAll();
    }
    protected void btnUpdateCategory_Click(object sender, EventArgs e)
    {
        if (mFormMode == FormViewMode.Insert)
        {
            new InventoryTask(mWebsite.ID).CreateCategory(int.Parse(fieldSelectedCategory.Value), txtCategoryName.Text, "", "", "default", User.Identity.Name);
        }
        else
        {
            Category cat = Category.Get(_categoryId);
            if (cat == null) return;
            new InventoryTask(mWebsite.ID).UpdateCategory(cat.ID, int.Parse(fieldSelectedCategory.Value), txtCategoryName.Text, "", "", null, User.Identity.Name);
        }
        mWebsite.NeedsPublish = true;
        Configuration.GetCurrentSession().Save(mWebsite);
        Configuration.GetCurrentSession().Flush();

        ResetForm();
    }

    private void ResetForm()
    {
        txtCategoryName.Text = "";
        tvCategorySelector.Nodes.Clear();
        tvCategorySelector.DataBind();
        mFormMode = FormViewMode.Insert;
        btnShowCreateCategoryForm.Enabled = true;
        panelAddEditCategory.Visible = false;
    }

    protected void btnShowCreateCategoryForm_Click(object sender, EventArgs e)
    {
        btnShowCreateCategoryForm.Enabled = false;
        panelAddEditCategory.Visible = true;

        mFormMode = FormViewMode.Insert;

        if (_categoryId != 0)
        {
            Category cat = Category.Get(_categoryId);
            if (cat == null) return;
            linkCustomize.Visible = false;
            string parentValue = cat.ID.ToString();
        }
        btnShowCreateCategoryForm.Enabled = false;
        panelAddEditCategory.Visible = true;
    }
    /*
    protected void tvCategories_SelectedNodeChanged(object sender, EventArgs e)
    {
        mFormMode = FormViewMode.Edit;
        Category cat = Configuration.GetCurrentSession().Get<Category>(int.Parse(tvCategories.SelectedValue));

        btnEdit.Enabled = true;
        btnEdit.Text = "Edit " + cat.Title;

        btnCustomize.Text = "Customise " + cat.Title;
        btnCustomize.Enabled = true;
    }

    private bool SelectNode(TreeNode parentNode, string Value)
    {
        foreach (TreeNode node in parentNode.ChildNodes)
        {
            if (node.Value == Value)
            {
                node.Select();
                return true;
            }
            else
            {
                if (SelectNode(node, Value))
                    return true;
            }
        }

        return false;
    }
     * */
    protected void btnCancel_Click(object sender, EventArgs e)
    {
        ResetForm();
    }
    protected void btnEdit_Click(object sender, EventArgs e)
    {
        mFormMode = FormViewMode.Edit;
        Category cat = Category.Get(_categoryId);
        if (cat == null) return;
        txtCategoryName.Text = cat.Title;
        linkCustomize.NavigateUrl = "CustomiseCategory.aspx?id=" + cat.ID.ToString();
        string parentValue = cat.ParentID.ToString();
        fieldSelectedCategory.Value = parentValue;

        foreach (TreeNode node in tvCategorySelector.Nodes)
        {
            if (node.Value == parentValue)
            {
                node.Select();
                break;
            }
            else
            {
                //if (SelectNode(node, parentValue))
                    //break;
            }
        }
        linkCustomize.Visible = true;

        btnShowCreateCategoryForm.Enabled = false;
        panelAddEditCategory.Visible = true;

    }
    
    protected void btnCustomize_Click(object sender, EventArgs e)
    {
        Response.Redirect("CustomiseCategory.aspx?id=" + _categoryId);
    }
    
    protected void lbMoveUp_Click(object sender, EventArgs e)
    {
        new InventoryTask(mWebsite.ID).CategoryOrderUp(_categoryId, User.Identity.Name);

        if (!mWebsite.NeedsPublish)
        {
            Configuration.GetCurrentSession().Save(mWebsite);
            Configuration.GetCurrentSession().Flush();
        }
        ResetForm();
        DataBind();
    }
    protected void lbMoveDown_Click(object sender, EventArgs e)
    {
        new InventoryTask(mWebsite.ID).CategoryOrderDown(_categoryId, User.Identity.Name);
        if (!mWebsite.NeedsPublish)
        {
            Configuration.GetCurrentSession().Save(mWebsite);
            Configuration.GetCurrentSession().Flush();
        }
        ResetForm();
        DataBind();
    }

    //  IMPORTANT: This must be public, not protected.  The adapters OnAdapted... event attributes only work if you
    //  equate them to the names of public event delegate methods.
    public void tvCategorySelector_OnSelectedNodeChanged(object sender, EventArgs e)
    {
        fieldSelectedCategory.Value = tvCategorySelector.SelectedNode.Value;
    }

   
}
